package com.luobo.pcsdepositmanage.easyexcel.listener.basic;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

@Data
public class MultiLineToSingleListener  extends AnalysisEventListener<Map<Integer, Object>> {
    private static final Logger LOGGER = LoggerFactory.getLogger(MultiLineToSingleListener.class);
    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 10000;
    List<Map<Integer, Object>> list = new ArrayList<Map<Integer, Object>>();

    @Override
    public void invoke(Map<Integer, Object> data, AnalysisContext context) {
//        LOGGER.info("data:",data.toString());

        String dealData = (String)data.get(1);

        String dealData2 = null;

        dealData2 = dealData.replaceAll("'","").replaceAll("’","").replaceAll("、","|").replaceAll("/","|").replaceAll(",","|").replaceAll("/","|").replaceAll("\\s+","|").replaceAll("[\\t\\n\\r]","|");
        String[] resultArray = dealData2.split("\\|");

        Set<String> stringSet = new HashSet<>();
        Collections.addAll(stringSet,resultArray);
        List<Map<Integer,Object>> resultMapList = new ArrayList<>();
        for (String string : stringSet) {
            Map<Integer,Object> map = new HashMap<>(data);
            map.put(2,string);
            resultMapList.add(map);
        }

//        String resultString = String.join("|",stringSet);
//        data.put(1,resultString);

        list.addAll(resultMapList);
        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        LOGGER.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        LOGGER.info("{}条数据，开始存储数据库！", list.size());
        LOGGER.info("存储数据库成功！");
    }
}
